package com.cheng.student.controller.servlet;

import com.cheng.student.beans.StudentFull;
import com.cheng.student.dao.InsertFailedException;
import com.cheng.student.service.StudentServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.*;
import java.util.List;
//1
@WebServlet(name = "ExcelInServlet", value = "/teacher/ExcelInServlet")
public class ExcelStudentInServlet
        extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        //校验
        String rowsS = request.getParameter("rows");
        if(rowsS == null || "".equals(rowsS))
        {
            response.getWriter().write("请输入行数");
        }
        int rows = 0;
        try
        {
            rows = Integer.parseInt(rowsS);
        }
        catch (NumberFormatException e)
        {
            response.getWriter().write("行数有误，请重新输入");
            return;
        }
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        InputStream inputStream = null;
        try
        {
            List<FileItem> fileItem = servletFileUpload.parseRequest(request);
            inputStream = fileItem.get(0).getInputStream();
        }
        catch (FileUploadException e)
        {
            response.getWriter().write("文件错误");
            return;
        }

        StudentServiceImpl studentService = new StudentServiceImpl();

        try
        {
            studentService.insertStudentsByExcel(inputStream, rows);
        }
        catch (InsertFailedException e)
        {
            response.getWriter().write("请检查学生" + e.getStudent().getXM());
            return;
        }
        catch (Exception e)
        {
            response.getWriter().write("文件有问题，请检查");
            return;
        }
        response.getWriter().write("添加成功，恭喜你");
    }
}
